package com.hyyt.shopjsp.finance.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hyyt.shopjsp.basic.pojo.BasicUsers;
import com.hyyt.shopjsp.basic.service.IBasicActorPurviewService;
import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.finance.pojo.ShopMallCoinWithDrawals;
import com.hyyt.shopjsp.finance.pojo.ShopSupplierMallCoinDetail;
import com.hyyt.shopjsp.finance.service.IShopMallCoinWithDrawalsService;
import com.hyyt.shopjsp.finance.service.IShopSupplierMallCoinDetailService;
import com.hyyt.shopjsp.store.info.pojo.ShopShopInfo;
import com.hyyt.shopjsp.store.info.service.IShopShopInfoService;
import com.hyyt.shopjsp.util.common.EnumUtils;
import com.hyyt.shopjsp.util.common.Page;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.export.ExportExcel;
import com.hyyt.shopjsp.util.json.FastJsonUtils;

/**
 * Copyright (c) 2017 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 * @author Wang Youchun on 2017/4/26 0024下午 15:43.
 */
@Controller
@RequestMapping("/back/shopMallCoinWithdrawals")
public class ShopMallCoinWithDrawalsController extends BaseController {
	private Logger log = Logger.getLogger(ShopMallCoinWithDrawalsController.class);
	private String basePath = "/back/shop/shopMallCoinWithdrawals/";
	
	@Resource
	private IShopMallCoinWithDrawalsService shopMallCoinWithDrawalsService;//供应商商城币提现service
	@Resource
	private IShopShopInfoService shopShopInfoService;//店铺service
	@Resource
	private IShopSupplierMallCoinDetailService shopSupplierMallCoinDetailService;//供应商商城币收支明细service
	/**
	 * 跳转店铺金币提现页面
	 *
	 * @return 进入指定页面
	 */
	@RequestMapping("gotoShopMallCoinWithdrawalsPage")
	public String gotoShopMallCoinWithdrawalsPage(){
        return basePath + "shopMallCoinWithdrawalsList";
	}

	/**
	 * 供应商金币提现列表
	 * @param payeeName 收款人名称
	 * @param serialNumber 流水号
	 * @param beginTime 交易开始时间
	 * @param endTime 交易结束时间
	 * @param page 分页
	 * @param response 结果集
	 */
	@RequestMapping(value="listShopMallCoinWithdrawals",method=RequestMethod.POST)
	@ResponseBody
	public void listShopMallCoinWithdrawals(String payeeName,String serialNumber,String beginTime,String endTime,Page page, HttpServletResponse response){
		Map<String, Object> params=new HashMap<>();
		if(Utils.objectIsNotEmpty(payeeName)){
			params.put("payeeName", payeeName.trim());
		}
		if(Utils.objectIsNotEmpty(serialNumber)){
			params.put("serialNumber", serialNumber.trim());
		}
		if(Utils.objectIsNotEmpty(beginTime)){
			params.put("beginTime", beginTime);
		}
		if(Utils.objectIsNotEmpty(endTime)){
			params.put("endTime", endTime);
		}
		params.put("sortColumns", "tradeTime desc");
		int totalRecordCount =shopMallCoinWithDrawalsService.countShopMallCoinWithDrawals(params);
		page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
		List<ShopMallCoinWithDrawals> shopMallCoinWithDrawalsList =shopMallCoinWithDrawalsService.queryShopMallCoinWithDrawals(params, page.getPageRecordBeginIndex(), page.getPageSize());
		params.clear();
		params.put("total", totalRecordCount);// total键 存放总记录数，必须的
		params.put("rows", shopMallCoinWithDrawalsList);// rows键 存放每页记录 list
		ResultMsg.create(params, response);  //把内容发送到页面
	}

	/**
	 * 审核金币提现申请
	 * @param shopMallCoinWithDrawals
	 * @return
	 */
	@RequestMapping(value="saveOrUpdateShopMallCoinWithdrawalsObject",method=RequestMethod.POST)
	@ResponseBody
	public ResultMsg saveOrUpdateShopMallCoinWithdrawalsObject(ShopMallCoinWithDrawals shopMallCoinWithDrawals){
		boolean flag=false;
		Map<String, Object> params=new HashMap<>();
		BasicUsers basicUsers = getSessionUsers();//获得session
		ShopMallCoinWithDrawals mallcoinWithdrawals = shopMallCoinWithDrawalsService.loadShopMallCoinWithDrawals(shopMallCoinWithDrawals.getDetailId());
		if(shopMallCoinWithDrawals.getState()==3|| shopMallCoinWithDrawals.getState()==5){
			params.put("payeeId", mallcoinWithdrawals.getPayeeId());
			ShopShopInfo shopShopinfo= shopShopInfoService.loadShopInfoByCustomerId(params);
			params.clear();
			ShopSupplierMallCoinDetail sc=new ShopSupplierMallCoinDetail();
			sc.setSupplierId(shopShopinfo.getShopInfoId());//客户ID
			sc.setSupplierLoginName(shopShopinfo.getCustomerName());//供应商账号
			sc.setType(4);//取现失败
			//提现金币数
			BigDecimal multiply = mallcoinWithdrawals.getTransactionAmount().multiply(new BigDecimal(mallcoinWithdrawals.getWithdrawBL()));
			sc.setTradMallCoin(multiply);
			//查询出最后一条交易记录的余额
			params.put("supplierId", shopShopinfo.getShopInfoId());
			List<ShopSupplierMallCoinDetail> findObjects=shopSupplierMallCoinDetailService.querySupplierMallCoinDetailBySupplierId(params);
			if(findObjects!=null){
				ShopSupplierMallCoinDetail supplierMallCoinDetail=findObjects.get(0);
				BigDecimal subtract = supplierMallCoinDetail.getTotalInPut().add(multiply);
				sc.setTotalInPut(subtract);//总收入
				sc.setTotalOutPut(supplierMallCoinDetail.getTotalOutPut());
			}
			Timestamp tradingTime=new Timestamp(System.currentTimeMillis());//获取系统当前Timestamp
			sc.setTradingTime(tradingTime);
			shopSupplierMallCoinDetailService.updateShopSupplierMallCoinDetail(sc);
		}
		Timestamp updateTime=new Timestamp(System.currentTimeMillis());//获取系统当前Timestamp
		Timestamp reviewerDate=new Timestamp(System.currentTimeMillis());//获取系统当前Timestamp
		mallcoinWithdrawals.setState(shopMallCoinWithDrawals.getState());
		mallcoinWithdrawals.setServerMessage(shopMallCoinWithDrawals.getServerMessage());
		mallcoinWithdrawals.setUpdateTime(updateTime);
		mallcoinWithdrawals.setReviewer(basicUsers.getUserName());
		mallcoinWithdrawals.setReviewerDate(reviewerDate);
		shopMallCoinWithDrawalsService.updateShopMallCoinWithDrawals(mallcoinWithdrawals);
		flag=true;
		return ResultMsg.create(flag);
	}

	/**
	 * 获取一条记录
	 * @param detailId
	 * @return
	 */
	@RequestMapping(value="getShopMallCoinWithdrawalsById",method=RequestMethod.POST)
	@ResponseBody
	public ResultMsg getShopMallCoinWithdrawalsById(Integer detailId){
		 if(Utils.objectIsNotEmpty(detailId)){
			ShopMallCoinWithDrawals shopMallCoinWithDrawals = shopMallCoinWithDrawalsService.loadShopMallCoinWithDrawals(detailId);
			return ResultMsg.create(true, null, FastJsonUtils.toJSONString(shopMallCoinWithDrawals));
		}
		return ResultMsg.create(false);
	}

	/**
	 * 导出店铺金币明细Excel
	 * @param response
	 * @param request
	 */
	@RequestMapping("exportShopMallCoinWithdrawalsExcel")
	public void exportShopMallCoinWithdrawalsExcel(String payeeName,String serialNumber,String beginTime,String endTime,HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
		Map<String, Object> params=new HashMap<>();
		if(Utils.objectIsNotEmpty(payeeName)){
			//用于get请求强转，防止中文乱码
			payeeName= new String(payeeName.trim().getBytes("iso8859-1"),"UTF-8");
			params.put("payeeName", payeeName);
		}
		if(Utils.objectIsNotEmpty(serialNumber)){
			params.put("serialNumber", serialNumber.trim());
		}
		if(Utils.objectIsNotEmpty(beginTime)){
			params.put("beginTime", beginTime);
		}
		if(Utils.objectIsNotEmpty(endTime)){
			params.put("endTime", endTime);
		}
		params.put("sortColumns", "tradeTime desc");
		List<ShopMallCoinWithDrawals> shopMallCoinWithDrawalsList =shopMallCoinWithDrawalsService.queryShopMallCoinWithDrawals(params);
		SimpleDateFormat formatter = new SimpleDateFormat(EnumUtils.DataFormat.Y_M_D_H_m_s.getValue());
		List<Map<String,Object>> mallDetailList = new ArrayList<>();
		if(shopMallCoinWithDrawalsList !=null&& shopMallCoinWithDrawalsList.size()>0){
			for (ShopMallCoinWithDrawals mallcoinWithdrawals : shopMallCoinWithDrawalsList) {
				 Map<String,Object> map = new HashMap<>();
				 map.put("payeeName", mallcoinWithdrawals.getPayeeName());
				 map.put("shopName",mallcoinWithdrawals.getShopName());
				 map.put("withdrawBL", mallcoinWithdrawals.getWithdrawBl());
				 map.put("serialNumber",mallcoinWithdrawals.getSerialNumber());
				 map.put("transactionAmount",mallcoinWithdrawals.getTransactionAmount());
				 switch (mallcoinWithdrawals.getState()){
				 	case 1:
				 		map.put("state","申请提现");
				 		break;
				 	case 2:
				 		map.put("state","平台审核通过");
				 		break;
				 	case 3:
				 		map.put("state","平台审核未通过");
				 		break;
				 	case 4:
				 		map.put("state","平台支付完成");
				 		break;
				 	case 5:
				 		map.put("state","平台支付失败");
				 		break;
				 }
				 map.put("reviewer",mallcoinWithdrawals.getReviewer());
				 map.put("tradeTime",formatter.format(mallcoinWithdrawals.getTradeTime()));
				 if(Utils.objectIsNotEmpty(mallcoinWithdrawals.getReviewerDate())){
					 map.put("reviewerDate",formatter.format(mallcoinWithdrawals.getReviewerDate()));
				 }else{
					 map.put("reviewerDate","");
				 }
				 mallDetailList.add(map);
			}
		}
		String fileName = "店铺金币提现明细";
		String columnNames[] = {"收款人","店铺名称","提现比例","流水号","交易金额","审核状态","审核人","交易时间","审核时间"};
		String keys[] = {"payeeName","shopName","withdrawBL","serialNumber","transactionAmount","state","reviewer","tradeTime","reviewerDate"};
		try {
            ExportExcel.download(fileName,mallDetailList,columnNames,keys,request,response);
        } catch (IOException e) {
            logger.error("导出Excel失败！");
        }
	}
}